package com.shigu.admin.common.service;

import com.opentae.data.mall.beans.DiyFunction;
import com.opentae.data.mall.beans.DiyPage;
import com.opentae.data.mall.beans.DiySearchParam;
import com.opentae.data.mall.beans.DiySql;
import com.opentae.data.mall.examples.DiyFunctionExample;
import com.opentae.data.mall.examples.DiySearchParamExample;
import com.opentae.data.mall.examples.DiySqlExample;
import com.opentae.data.mall.interfaces.DiyFunctionMapper;
import com.opentae.data.mall.interfaces.DiyPageMapper;
import com.opentae.data.mall.interfaces.DiySearchParamMapper;
import com.opentae.data.mall.interfaces.DiySqlMapper;
import com.shigu.admin.common.enums.PageType;
import com.shigu.admin.common.enums.ParamType;
import com.shigu.admin.common.freemarker.StringFreemarkerUtil;
import com.shigu.admin.common.vo.*;
import com.shigu.component.utils.BeanMapper;
import com.shigu.exceptions.BaohuoException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 公共页部分
 * Created by zhaohongbo on 17/7/10.
 */
@Service
public class CommonAdminService {

    @Autowired
    DiyPageMapper diyPageMapper;

    @Autowired
    DiySqlMapper diySqlMapper;

    @Autowired
    DiyFunctionMapper diyFunctionMapper;

    @Autowired
    DiySearchParamMapper diySearchParamMapper;

    /**
     * 页面信息查询
     * @param pageId
     * @return
     */
    public PageInfoVO selPageById(Long pageId) throws BaohuoException {
        if (pageId == null) {
            return null;
        }
        DiyPage page=diyPageMapper.selectByPrimaryKey(pageId);
        if (page == null) {
            return null;
        }
        PageInfoVO pageInfo=new PageInfoVO();
        pageInfo.setHtml(page.getHtmlContent());
        pageInfo.setType(PageType.selByValue(page.getType()));
        if (pageInfo.getType().equals(PageType.OUTER)) {
            pageInfo.setOuterUrl(page.getOuterUrl());
            return pageInfo;
        }
        String fieldMap=page.getFieldMap();//列对应关系,key:value,
        if (fieldMap != null) {
            List<String> fieldTitle=new ArrayList<>();
            List<String> fieldVariables=new ArrayList<>();
            String[] fields=fieldMap.split(",");
            for(String f:fields){
                String[] farr=f.split(":");
                fieldTitle.add(farr[1]);
                fieldVariables.add(farr[0]);
            }
            pageInfo.setFieldTitles(fieldTitle);
            pageInfo.setFieldVariables(fieldVariables);
        }
        //处理查询条件
        DiySearchParamExample searchParamExample=new DiySearchParamExample();
        searchParamExample.createCriteria().andPageIdEqualTo(pageId);
        List<DiySearchParam> params=diySearchParamMapper.selectByExample(searchParamExample);
        if(params.size()>0){
            List<ParamVO> paramVOs= BeanMapper.mapList(params,ParamVO.class);
            Map<Long,DiySearchParam> map= BeanMapper.list2Map(params,"paramId",Long.class);
            for(ParamVO param:paramVOs){
                //处理options、defaultValue
                DiySearchParam diyParam=map.get(param.getParamId());
                param.setPtype(ParamType.selByValue(diyParam.getType()));
                if(param.getPtype()== ParamType.INPUT){
                    param.setDefaultValue(diyParam.getContent());
                }else if(param.getPtype()== ParamType.SELECT){
                    String content=diyParam.getContent();
                    if (content != null) {
                        List<OptionVO> optionVOs=new ArrayList<>();
                        String[] kvs=content.split(",");
                        for(String kv:kvs){
                            optionVOs.add(new OptionVO(kv));
                        }
                        param.setOptions(optionVOs);
                    }
                }
            }
            pageInfo.setParams(paramVOs);
        }
        //处理sql
        DiySqlExample sqlExample=new DiySqlExample();
        sqlExample.setOrderByClause("sql_id asc");
        sqlExample.createCriteria().andUseForEqualTo(1).andTargetIdEqualTo(pageId);
        List<DiySql> diySqls=diySqlMapper.selectByExample(sqlExample);
        pageInfo.setSqlList(BeanMapper.mapList(diySqls, SqlVO.class));
        //处理功能
        DiyFunctionExample functionExample=new DiyFunctionExample();
        functionExample.createCriteria().andPageIdEqualTo(pageId);
        List<DiyFunction> functions=diyFunctionMapper.selectByExample(functionExample);
        List<FunctionVO> functionVOs=BeanMapper.mapList(functions,FunctionVO.class);
        List<FunctionVO> pageFunctionVOs=new ArrayList<>();
        List<FunctionVO> butFunctionVOs=new ArrayList<>();
        for(FunctionVO fun:functionVOs){
            //把js进行sql对应一下
            if(StringUtils.isNotEmpty(fun.getJsScript())){
                DiySqlExample diySqlExample=new DiySqlExample();
                diySqlExample.setOrderByClause("sql_id asc");
                diySqlExample.createCriteria().andUseForEqualTo(2).andTargetIdEqualTo(fun.getFunctionId());
                List<DiySql> sqls=diySqlMapper.selectByExample(diySqlExample);
                if(sqls.size()>0){
                    Map<String,Object> sqlIdMap=new HashMap<>();
                    for(int i=0;i<sqls.size();i++){
                        sqlIdMap.put("SQL"+i,sqls.get(i).getSqlId());
                    }
                    try {
                        fun.setJsScript(StringFreemarkerUtil.parseString(sqlIdMap,fun.getJsScript()));
                    } catch (Exception e) {
                        throw new BaohuoException("js翻译异常"+e.getMessage());
                    }
                }
            }
            //归类存放
            if(fun.getLocationType()==1){
                pageFunctionVOs.add(fun);
            }else{
                butFunctionVOs.add(fun);
            }
        }
        if(pageFunctionVOs.size()>0){
            pageInfo.setPageFunctions(pageFunctionVOs);
        }
        if(butFunctionVOs.size()>0){
            pageInfo.setRowFunctions(butFunctionVOs);
        }
        return pageInfo;
    }

    /**
     * 翻译sql
     * @param sql
     * @return
     */
    public List<Map<String,Object>> selDiyList(Map<String,Object> data,String sql) throws BaohuoException {
        try {
            if(StringUtils.isEmpty(sql)){
                return new ArrayList<>();
            }
            sql= StringFreemarkerUtil.parseString(data,sql);
            if(sql.startsWith("select")){
                return diySqlMapper.selDiyList(sql);
            }else if(sql.startsWith("delete")){
                diySqlMapper.deleteDiy(sql);
            }else if(sql.startsWith("insert")){
                diySqlMapper.insertDiy(sql);
            }else if(sql.startsWith("update")){
                diySqlMapper.updateDiy(sql);
            }
            return new ArrayList<>();
        } catch (Exception e) {
            throw new BaohuoException("sql模板解决异常 "+e.getMessage());
        }
    }

    /**
     * 集合转成单个
     * @param params
     * @return
     */
    public Map<String,String> parseParamter(Map<String,String[]> params){
        Map<String,String> resultMap=new HashMap<>();
        if(params == null){
            return resultMap;
        }
        Iterator<String> keyIt=params.keySet().iterator();
        while(keyIt.hasNext()){
            String key=keyIt.next();
            String[] values=params.get(key);
            if (values != null && values.length>0 && StringUtils.isNotEmpty(values[0])) {
                resultMap.put(key,values[0]);
            }
        }
        return resultMap;
    }

    public SqlVO selSqlVO(Long sqlId) throws BaohuoException {
        DiySql sql=diySqlMapper.selectByPrimaryKey(sqlId);
        if (sql == null) {
            throw new BaohuoException("sql不存在");
        }
        SqlVO sqlVO=BeanMapper.map(sql,SqlVO.class);
        return sqlVO;
    }

    public SqlVO selSqlVOByFunId(Long funId) throws BaohuoException {
        DiySqlExample example=new DiySqlExample();
        example.createCriteria().andTargetIdEqualTo(funId);
        example.setStartIndex(0);
        example.setEndIndex(1);
        List<DiySql> sqls=diySqlMapper.selectByConditionList(example);
        if (sqls.size()==0) {
            throw new BaohuoException("sql不存在");
        }
        SqlVO sqlVO=BeanMapper.map(sqls.get(0),SqlVO.class);
        return sqlVO;
    }

    /**
     * 查一个方法
     * @param functionId
     * @return
     * @throws BaohuoException
     */
    public FunctionVO selFunctionById(Long functionId) throws BaohuoException {
        DiyFunction diyFunction=diyFunctionMapper.selectByPrimaryKey(functionId);
        if (diyFunction == null) {
            throw new BaohuoException("方法不存在");
        }
        FunctionVO functionVO= BeanMapper.map(diyFunction,FunctionVO.class);
        if(functionVO.getType()==2){//只有请求类的,才有sql
            DiySqlExample sqlExample=new DiySqlExample();
            sqlExample.setOrderByClause("sql_id asc");
            sqlExample.createCriteria().andTargetIdEqualTo(functionId).andUseForEqualTo(2);
            functionVO.setSqlList(BeanMapper.mapList(diySqlMapper.selectByExample(sqlExample),SqlVO.class));
        }
        return functionVO;
    }
}
